import React, { useLayoutEffect, useState } from 'react';

import { Icon } from 'antd';
import { ActivityIndicator, InputItem, Modal, Toast } from 'antd-mobile';
import { createForm } from 'rc-form';
import { useMount } from 'react-use';
import { router, withRouter } from 'umi';

import { defaultFormatResult, useRequest } from '@/hooks';
import useDictionary from '@/hooks/useDictionary';
import CustomNavBar from '@/pages/EntryManage/mobile/components/CustomNavBar';
import EntryMetaTag from '@/pages/EntryManage/mobile/components/EntryMetaTag';
import { fetchEmployeeArchivesData, saveEmployeeEmergencyData } from '@/pages/EntryManage/services';
import { useFormChange } from '@/pages/RecruitEmail/hooks';
import { Button, EditListItem, Picker } from '@/pages/RecruitEmail/mobile/components';

import styles from './index.less';

const PhoneType = props => (
    <div onClick={props.onClick} style={{ flex: 1, fontSize: 16, color: '#bcc1cd' }}>
        {props.extra} <Icon style={{ fontSize: 10 }} type="caret-down" />
    </div>
);

/**
 * 入职员工紧急联系人
 */
const EntryEmployeeEmergencyContactMobile = ({ form, location }) => {
    const [pageError, setPageError] = useState();
    const { query } = location;
    const { entryPersonnelCode } = query;
    const { getFieldProps, resetFields } = form;
    const [emergencyRelationshipList] = useDictionary('emergencyRelationship', { textKey: 'label' });
    const { hasFormChange, initialForm } = useFormChange(form);
    // 获取数据
    const {
        data: employeeArchivesData,
        loading: employeeArchivesLoading,
        error: fetchEmployeeArchivesInfoError
    } = useRequest(() => fetchEmployeeArchivesData(entryPersonnelCode), {
        refreshDeps: [entryPersonnelCode],
        ready: !!entryPersonnelCode,
        ...defaultFormatResult,
        onSuccess: () => {
            initialForm();
        }
    });

    useMount(() => {
        if (!entryPersonnelCode) {
            initialForm();
        }
    });

    // 提交
    const { run: submitRun, loading: submitLoading } = useRequest(submitData => saveEmployeeEmergencyData(submitData), {
        manual: true
    });

    // 提交
    const handleSubmit = isContinueAdd => {
        form.validateFields((err, values) => {
            if (!err) {
                const submitData = {
                    entryPersonnelCode,
                    emergencyContact: values.emergencyContact,
                    emergencyRelationship: values.emergencyRelationship?.length
                        ? values.emergencyRelationship[0]
                        : null,
                    emergencyTelephone: values.emergencyTelephone,
                    emergencyAreaCode: values?.emergencyAreaCode?.length ? values.emergencyAreaCode[0] : null
                };
                // 提交
                submitRun(submitData).then(res => {
                    if (res.code === 10000) {
                        Toast.info('保存成功', 3, null, false);
                        if (isContinueAdd) {
                            resetFields();
                        } else {
                            history.goBack();
                        }
                    } else {
                        Toast.info(res.msg);
                    }
                });
            } else {
                const errorList = Object.values(err);
                if (errorList && errorList.length > 0) {
                    const { errors } = errorList[0];
                    Toast.info(errors[0]?.message, 3, null, false);
                }
            }
        });
    };

    const handleLeftClick = () => {
        if (hasFormChange()) {
            Modal.alert('存在未保存的内容，确定退出吗？', '', [
                { text: '取消' },
                {
                    text: '确定',
                    onPress: () => {
                        history.goBack();
                    }
                }
            ]);
        } else {
            history.goBack();
        }
    };

    useLayoutEffect(() => {
        // 参数校验
        if (!entryPersonnelCode) {
            setPageError('参数无效');
        }
    }, [entryPersonnelCode]);

    if (pageError || fetchEmployeeArchivesInfoError) {
        return (
            <div className={styles.pageError}>
                {pageError?.msg || fetchEmployeeArchivesInfoError?.msg || '加载错误'}
            </div>
        );
    }

    return (
        <>
            {(employeeArchivesLoading || submitLoading) && <ActivityIndicator toast text="正在加载" />}
            {employeeArchivesData ? (
                <div className={styles.entryMobileContainer}>
                    <EntryMetaTag />
                    <CustomNavBar onLeftClick={handleLeftClick}>紧急联系人</CustomNavBar>
                    <div className="formContainer formContainerFixed">
                        <EditListItem title="姓名" showArrow={false}>
                            <InputItem
                                {...getFieldProps('emergencyContact', {
                                    initialValue: employeeArchivesData?.emergencyContact || '',
                                    rules: [
                                        { required: true, message: '请输入姓名' },
                                        {
                                            min: 2,
                                            max: 50,
                                            message: '姓名字数范围:2到50个字符'
                                        }
                                    ]
                                })}
                                clear
                                placeholder="请输入姓名"
                            />
                        </EditListItem>
                        <Picker
                            title="与本人关系"
                            data={emergencyRelationshipList}
                            className={styles.customPicker}
                            cols={1}
                            {...getFieldProps('emergencyRelationship', {
                                initialValue: employeeArchivesData?.emergencyRelationship
                                    ? [employeeArchivesData?.emergencyRelationship]
                                    : undefined,
                                rules: [{ required: true, message: '请选与本人关系' }]
                            })}
                        >
                            <EditListItem title="与本人关系">请选择</EditListItem>
                        </Picker>
                        <EditListItem title="手机号" showArrow={false}>
                            <div style={{ display: 'flex', alignItems: 'center' }}>
                                <Picker
                                    title="选择国际电话区号"
                                    className={styles.customPicker}
                                    data={[
                                        { label: '+86', value: '86' },
                                        { label: '+65', value: '65' }
                                    ]}
                                    {...getFieldProps('emergencyAreaCode', {
                                        initialValue: [employeeArchivesData?.emergencyAreaCode || '86']
                                    })}
                                >
                                    <PhoneType />
                                </Picker>
                                <div className={styles.mobileAddStyle}>
                                    <InputItem
                                        {...getFieldProps('emergencyTelephone', {
                                            initialValue: employeeArchivesData?.emergencyTelephone || '',
                                            rules: [
                                                {
                                                    required: true,
                                                    validator(rule, value, callback) {
                                                        const regex = /^\d{7,11}$/;
                                                        if (!value) {
                                                            callback('手机号不能为空');
                                                        } else if (!regex.test(value)) {
                                                            callback('手机号只能输入7-11位数字');
                                                        }
                                                        callback();
                                                    }
                                                }
                                            ]
                                        })}
                                        clear
                                        placeholder="请输入手机号"
                                    />
                                </div>
                            </div>
                        </EditListItem>
                    </div>
                    <div className="formControls">
                        <Button type="primary" onClick={handleSubmit}>
                            保存
                        </Button>
                    </div>
                </div>
            ) : null}
        </>
    );
};

export default withRouter(createForm()(EntryEmployeeEmergencyContactMobile));
